<template>
	<view class="content">
		<view class="limit">
			剩余推荐数：<text class="limit-number">2</text>次，
			已用推荐数：<text class="limit-number">1</text> 次
		</view>
		<uni-card title="目标岗位" :is-shadow="true" margin="10px">
			<template v-slot:title>
				<view class="space-between" style="padding: 10px;border-bottom: 1px solid #eee;">
					<text style="color: #3a3a3a;font-size: 15px;font-weight: bold;">目标岗位</text>
				</view>
			</template>
			<view class="position">
				<view class="item">
					<view class="logo">
						<image :src="position.companyLogo"></image>
					</view>
					<view class="job">
						<view class="title space-between">
							<view class="left">
								<text class="title-name">{{ position.postName }}</text>
							</view>
							<!-- <text class="right">{{ position.createTime }}</text> -->
						</view>
						<view class="company">
							{{ position.companyName }}
							<view class="height-line"></view>
							{{ position.companyStaffSize }}
							<view class="height-line"></view>
							{{ position.companyNature }}
						</view>
						<view class="desc">
							<text>{{position.salary}}<text v-if="position.unit != '元/月'">{{ position.unit }}</text></text>
						</view>
					</view>
				</view>
			</view>
		</uni-card>
		<uni-card title="推荐简历" :is-shadow="true" margin="10px">
			<template v-slot:title>
				<view class="space-between" style="padding: 10px;border-bottom: 1px solid #eee;">
					<text style="color: #3a3a3a;font-size: 15px;font-weight: bold;">推荐简历</text>
					<text style="font-size: 15px;color: #12ae85;" @click="selectResume">选择简历</text>
				</view>
			</template>
			<view class="resume">
				<view class="title" v-if="resume">
					<image class="right" v-if="resume.avatar" :src="resume.avatar"></image>
					<image class="right" v-else src="/static/img/head.png.png"></image>
					<view class="left">
						<view class="">
							<text :class="resume.ifRead?'name-read':'name'">{{resume.name}}</text>
						</view>
						<view class="skill">
							{{formatAge(resume.timeToWork)}}年
							<view class="height-line"></view>
							{{resume.education}}
							<view class="height-line"></view>
							{{formatAge(resume.birthday)}}岁
						</view>
					</view>
				</view>
				<view class="resume-null" v-else>暂无简历，请先选择简历</view>
			</view>
		</uni-card>
		<uni-card title="推荐信" :is-shadow="true" margin="10px">
			<template v-slot:title>
				<view class="space-between" style="padding: 10px;border-bottom: 1px solid #eee;">
					<text style="color: #3a3a3a;font-size: 15px;font-weight: bold;">推荐信</text>
					<text style="font-size: 15px;color: #12ae85;" @click="autoCreate">AI生成</text>
				</view>
			</template>
			<view class="recommendation">
				<textarea :auto-height="true" v-model="recommendContent" maxlength="1500" placeholder="请输入推荐内容" />
			</view>
		</uni-card>
		<view class="btn" @click="startPush">开始推荐<text class="canuse">(剩 2 次)</text></view>

		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<view class="top">
					<text class="title">搜索简历</text>
					<text class="yzb yzb-shanchu" @click="closePop"></text>
				</view>
				<view class="search">
					<input @input="input" placeholder="请输入姓名搜索" />
				</view>
				<scroll-view scroll-y style="height: 600upx;" v-if="resumes.length>0">
					<radio-group @change="radioChange">
						<view class="resume" v-for="(item,index) in resumes" :key="index">
							<view class="title">
								<image class="right" :src="item.avatar"></image>
								<view class="left">
									<view class="">
										<text :class="item.ifRead?'name-read':'name'">{{item.name}}</text>
									</view>
									<view class="skill">
										{{formatAge(item.timeToWork)}}年
										<view class="height-line"></view>
										{{item.education}}
										<view class="height-line"></view>
										{{formatAge(item.birthday)}}岁
									</view>
								</view>
							</view>
							<view class="resume-dot">
								<radio :value="index" :checked="item.checked"></radio>
							</view>
						</view>
					</radio-group>
				</scroll-view>
				<view class="pop-none" v-else>
					无搜素记录
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		formatDate,
		calCurrentYear
	} from '@/common/date';
	import {
		mapState,
	} from 'vuex';
	import config from "@/config/index.config.js";
	export default {
		computed: {
			...mapState(['userInfo']),
		},
		data() {
			return {
				position: {},
				resume: null,
				resumes: [],
				recommendContent: '',
				query: {
					page: 1,
					limit: 50,
					keyword: ''
				},
				tempMsg:"",
				
				socketTask:null,
			}
		},
		onLoad(options) {
			this.position = JSON.parse(options.position);
			this.connect();
		},
		
		onUnload() {
			this.close();
		},
		
		onNavigationBarButtonTap() {
			this.$mRouter.push({
				route: this.$mRoutesConfig.robot,
				query: {
				}
			});
		},
		
		methods: {
			startPush() {
				if (!this.resume) {
					uni.showToast({
						icon: 'none',
						title: '请先选择推荐简历'
					})
					return;
				}
				if (!this.recommendContent) {
					uni.showToast({
						icon: 'none',
						title: '请先输入推荐信内容'
					})
					return;
				}
				if (this.recommendContent.length<50) {
					uni.showToast({
						icon: 'none',
						title: '推荐信内容不能少于50个字'
					})
					return;
				}
				let that=this;
				uni.showModal({
					title: '温馨提示',
					content: '确定要进行推荐？',
					showCancel: true,
					confirmText: '确定',
					success: function(res) {
						if (res.confirm) {
							that.doApply();
						}
					}
				});
			},

			/**
			 * 职位申请
			 */
			async doApply() {
				let param = {
					positionId: this.position.id,
					companyId: this.position.companyId,
					comMemberId: this.position.memberId,
					memberId:this.resume.memberId,
					referenceId: this.userInfo.id,
					referenceRole: this.userInfo.memberRole,
					referenceContent: this.recommendContent
				};
				let res = await this.$apis.updateApply(param);
				if (res) {
					uni.showModal({
						title: '推荐成功',
						content: '已减去1次推荐次数',
						showCancel: false,
						confirmText: '确定',
						success: function(res) {
							if (res.confirm) {
								uni.navigateBack();
							}
						}
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1000)
				}
			},

			async getResumeList() {
				let res = await this.$apis.getResumeList(this.query);
				if (res) {
					if (this.query.page == 1) {
						this.resumes = [];
					}
					let data = res.records;
					this.resumes = this.resumes.concat(data || []);
				}
			},

			input(e) {
				console.log("input==", e.detail.value);
				this.query.keyword = e.detail.value;
				this.getResumeList();
			},

			radioChange(e) {
				console.log("radioChange==", e.detail.value);
				this.resume = this.resumes[e.detail.value];
				this.closePop();
			},

			closePop() {
				this.$refs.popup.close();
			},
			selectResume() {
				this.resumes = [];
				this.$refs.popup.open("bottom")
			},
			
			formatSex(sex){
				if(sex==1){
					return '男'
				}else if(sex==2){
					return '女'
				}else{
					return ''
				}
			},
			
			//AI生成
			autoCreate() {
				//生成拼接信息
				// 姓名+性别+年龄+个人优势+学历  + 目标岗位
				// 推荐人
				if(!this.resume){
					uni.showToast({
						icon:'none',
						title:"请先选择简历"
					})
					return;
				}
				console.log("resume==",this.resume);
				// let info=this.resume.name+","+this.formatSex(this.resume.sex)+","+this.formatAge(this.resume.birthday)+"岁,"
				// 		+this.resume.personalSkill+","+this.resume.education+" 写一份给她的朋友"+this.userInfo.realname+"针对岗位"+this.position.postName+" 的推荐信"
				// console.log("info==",info);
				// this.send(info);
				this.createByAI();
			},
			
			//AI生成
			createByAI(){
				let that=this;
				uni.showModal({
					title: '提示',
					content: '确定AI生成推荐信？',
					success: res => {
						if (res.confirm) {
							that.doAI();
						}
					}
				});
			},
			
			async  doAI(){
				//获取AI拼接词
				let res = await this.$apis.getAiPrompt({
					type:2,//1-自荐信，2-推荐信
					positionId: this.position.id,
					memberId: this.resume.memberId,
					refererId:this.userInfo.id,
				});
				console.log("res===",res)
				if(res!=true){
					this.send(res);
				}
			},
			
			formatAge(birthday) {
				return calCurrentYear(birthday);
			},
			formatString(val) {
				return val.split(",");
			},
			formatCreateTime(time) {
				console.log("formatCreateTime", time);
				if (time == null || time === '') {
					return null;
				}
				let str = time.replace(/-/g, '/');
				let date = new Date(str);
				return formatDate(date, 'yyyy-MM-dd hh:mm');
			},
			
			//-----------------------------websocket部分------------------------------
			connect() {
				if (this.connected || this.connecting) {
					uni.showModal({
						content: '正在连接或者已经连接，请勿重复连接',
						showCancel: false,
					})
					return
				}
				this.connecting = true
				uni.showLoading({
					title: '连接中...',
				})
				this.socketTask=uni.connectSocket({
					url: config.wsUrl + '/api/ws/'+this.userInfo.id,
					// url: 'wss://kpapi.nkzfw.com/api/ws/'+this.userInfo.id,
					success(res) {
						// 这里是接口调用成功的回调，不是连接成功的回调，请注意
						console.log('uni.connectSocket success', res)
						uni.hideLoading();
					},
					fail(err) {
						// 这里是接口调用失败的回调，不是连接失败的回调，请注意
						console.log('uni.connectSocket fail', err)
						uni.hideLoading();
					},
				})
				this.socketTask.onOpen((res) => {
					if (this.pageVisible) {
						this.connecting = false
						this.connected = true
						uni.hideLoading()
			
						uni.showToast({
							icon: 'none',
							title: '连接成功',
						})
						console.log('onOpen', res)
					}
				})
				this.socketTask.onError((err) => {
					if (this.pageVisible) {
						this.connecting = false
						this.connected = false
						uni.hideLoading()
			
						uni.showModal({
							content: '连接失败，可能是websocket服务不可用，请稍后再试',
							showCancel: false,
						})
						console.log('onError', err)
					}
				})
			
				this.socketTask.onMessage((res) => {
					console.log('onMessage', res)
					if (res.data == "[DONE]") {
						this.tempMsg = '';
						return;
					}
					let json_data = JSON.parse(res.data)
					console.log('json_data', json_data)
					if(json_data.role){
						this.tempMsg = '';
					}else{
						if (!json_data.content) {
						}else{
							this.tempMsg = this.tempMsg + json_data.content;
							console.log('recommendContent', this.tempMsg)
						}
						this.recommendContent=this.tempMsg;
						this.$forceUpdate();
					}
				})
				
				this.socketTask.onClose((res) => {
					this.connected = false
					this.msg = ''
					console.log('onClose', res)
				})
			},
			
			send(msg) {
				uni.showToast({
					icon:'none',
					title:'开始生成'
				})
				this.socketTask.send({
					data: msg,
					success(res) {
						console.log(res)
					},
					fail(err) {
						console.log(err)
					},
				})
			},
			
			close() {
				this.socketTask.close({
					code: 1000,
					reason: 'close reason from client',
					success(res) {
						console.log('uni.closeSocket success', res)
					},
					fail(err) {
						console.log('uni.closeSocket fail', err)
					},
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f8f8f8;
	}

	.content {
		padding-bottom: 100upx;
	}

	.limit {
		display: flex;
		flex-direction: row;
		justify-content: center;
		color: #666;
		font-size: 28upx;
		padding: 20upx 0 10upx 0;

		.limit-number {
			padding: 0 10rpx;
			color: orange;
			font-weight: bold;
		}
	}

	.btn {
		position: fixed;
		width: 100%;
		bottom: 0;
		background-color: $main-color;
		color: #fff;
		text-align: center;
		padding: 10rpx 0;
		box-sizing: border-box;

		.canuse {
			margin-left: 15rpx;
		}
	}

	.position {
		.item {
			background-color: $bgcolor_white;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: flex-start;
			margin-bottom: 20upx;
			border-radius: 10upx;
			padding: 15upx;
		}

		.logo {
			margin-right: 20upx;
			border: #eee solid 2upx;
			border-radius: 10upx;

			image {
				width: 120upx;
				height: 120upx;
				border-radius: 10upx;
			}
		}

		.job {
			flex: 1;

			.title {
				.left {
					font-weight: bold;
					font-size: $uni-font-size-lg;
				}

				.title-name {
					font-weight: bold;
					font-size: $uni-font-size-lg;
				}

				.title-share {
					color: $main-color;
					border: 1upx solid $main-color;
					border-radius: 20upx 0upx;
					font-size: $uni-font-size-sm;
					margin-left: 20upx;
					padding: 3upx 10upx;
				}

				.right {
					color: #666;
				}
			}

			.company {
				color: $font-color-666;
				margin-top: 5upx;
				font-size: 26upx;
				display: flex;
				flex-direction: row;
				align-items: center;

				.height-line {
					height: 20upx;
					width: 4upx;
					background-color: $font-color-ccc;
					margin: 0 15upx;
				}
			}

			.desc {
				text {
					color: #666;
				}
			}
		}
	}

	.resume {
		display: flex;
		flex-direction: column;

		.title {
			display: flex;
			flex-direction: row;
			align-items: center;

			.left {
				margin-left: 20upx;
				display: flex;
				flex-direction: column;

				.name {
					font-weight: bold;
					font-size: $uni-font-size-lg;
				}

				.yzb-yirenzheng1 {
					font-weight: bold;
					font-size: 34upx;
					color: $uni-color-success;
					margin-right: 10upx;
				}

				.name-read {
					font-weight: bold;
					font-size: $uni-font-size-lg;
					color: $font-color-666;
				}

				.read-status {
					margin-left: 20upx;
					font-size: $uni-font-size-base;
					color: $font-color-red;
				}

				.yzb-nan {
					color: #12ae85;
					font-weight: bold;
					font-size: 34upx;
					margin-left: 10upx;
				}

				.yzb-nv {
					color: #FF6A6A;
					font-weight: bold;
					font-size: 34upx;
					margin-left: 10upx;
				}

				.skill {
					color: $font-color-666;
					margin-top: 5upx;
					font-size: $uni-font-size-base;
					display: flex;
					flex-direction: row;
					align-items: center;

					.height-line {
						height: 20upx;
						width: 4upx;
						background-color: $font-color-ccc;
						margin: 0 15upx;
					}
				}
			}

			.right {
				width: 120upx;
				height: 120upx;
				border-radius: 60upx
			}
		}

		.resume-null {
			width: 100%;
			text-align: center;
			padding: 50upx 0;
			color: #999;
		}
	}

	.recommendation {
		textarea{
			width: 100%;
			// background-color: #f8f8f8;
			border-radius: 1upx solid #eee;
			padding: 20upx 0;
		}
	}

	.space-between {
		display: flex;
		justify-content: space-between;
		flex-direction: row;
	}

	.popup-content {
		.top {
			position: relative;
			text-align: center;
			align-items: center;
			padding: 20upx;
			border-bottom: 2upx solid #eee;
			box-sizing: border-box;

			.title {
				font-weight: bold;
			}

			.yzb-shanchu {
				position: absolute;
				right: 0;
				padding-right: 20upx;
			}
		}

		.search {
			padding: 20upx;

			input {
				text-align: center;
				background-color: #fff;
				padding: 10upx;
				border-radius: 10upx;
				border: 1upx solid #eee;
				font-size: 28upx;
			}
		}

		.resume {
			padding: 15upx 20upx;
			border-bottom: 2upx solid #eee;
			display: flex;
			justify-content: space-between;
			flex-direction: row;
			align-items: center;

			.title {
				display: flex;
				flex-direction: row;
				align-items: center;

				.left {
					margin-left: 20upx;
					display: flex;
					flex-direction: column;

					.name {
						font-weight: bold;
						font-size: $uni-font-size-lg;
					}

					.skill {
						color: $font-color-666;
						margin-top: 5upx;
						font-size: $uni-font-size-base;
						display: flex;
						flex-direction: row;
						align-items: center;

						.height-line {
							height: 20upx;
							width: 4upx;
							background-color: $font-color-ccc;
							margin: 0 15upx;
						}
					}
				}

				.right {
					width: 100upx;
					height: 100upx;
					border-radius: 50upx
				}
			}
		}

		.pop-none {
			height: 600upx;
			text-align: center;
			box-sizing: border-box;
			padding-top: 200upx;
			color: #999;
		}
	}
</style>